"use client";
import { useState, useRef, useEffect } from "react";

// Agent 状态类型定义
interface AgentState {
  question: string;
  thought: string;
  action: string;
  actionInput: Record<string, unknown>;
  observation: string;
  answer: string;
  step: number;
}

// Multi-Agent 结果类型定义
interface CollaborateResult {
  individual_results: Record<string, string>;
  final_answer: string;
}

interface Message {
  id: string;
  type: "user" | "agent";
  content: string;
  steps?: AgentState[];
  timestamp: Date;
}

export default function AgentPage() {
  const [messages, setMessages] = useState<Message[]>([]); // 聊天消息列表
  const [input, setInput] = useState("");// 用户输入框内容
  const [agentType, setAgentType] = useState("react");// 当前选择的 Agent 类型
  const [loading, setLoading] = useState(false);// 请求加载状态
  const [streamEnabled, setStreamEnabled] = useState(true);// 是否启用流式输出
  const messagesEndRef = useRef<HTMLDivElement>(null);  // 用于滚动到底部的引用

  // 滚动到最新消息
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  // 监听 messages 变化，自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 发送消息逻辑
  const sendMessage = async () => {
    if (!input.trim() || loading) return; // 空内容或加载中不发送

    // 添加用户消息到列表
    const userMessage: Message = {
      id: Date.now().toString(),
      type: "user",
      content: input,
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    const currentInput = input;
    setInput("");// 清空输入框
    setLoading(true);// 开始加载

    try {
      // 如果启用流式输出且是 ReAct Agent
      if (streamEnabled && agentType === "react") {
        await handleStreamResponse(currentInput);
      } else {
        await handleNormalResponse(currentInput);
      }
    } catch (error: unknown) {
      // 改进错误处理
      let errorMessage = "发生未知错误";
      if (error instanceof Error) {
        errorMessage = error.message;
      } else if (typeof error === 'string') {
        errorMessage = error;
      }

      const errorMsg: Message = {
        id: (Date.now() + 1).toString(),
        type: "agent",
        content: `❌ 错误：${errorMessage}`,
        timestamp: new Date()
      };
      setMessages(prev => [...prev, errorMsg]);
    } finally {
      setLoading(false);
    }
  };

  // 处理流式响应
  const handleStreamResponse = async (message: string) => {
    const response = await fetch("/api/agent", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message, agentType, stream: true })
    });
console.log(response)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) {
      throw new Error("无法读取响应流");
    }

    // 创建一个临时消息用于流式更新
    const tempMessageId = (Date.now() + 1).toString();
    let streamContent = "";

    setMessages(prev => [...prev, {
      id: tempMessageId,
      type: "agent",
      content: "",
      timestamp: new Date()
    }]);

    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        
        // 检查是否是完成或错误标记
        if (chunk.includes('---DONE---')) {
          break;
        }
        if (chunk.includes('---ERROR:')) {
          const errorMsg = chunk.match(/---ERROR: (.+?)---/)?.[1] || "未知错误";
          throw new Error(errorMsg);
        }
        
        // 累积内容
        streamContent += chunk;

        // 实时更新消息（打字机效果）
        setMessages(prev => prev.map(msg =>
          msg.id === tempMessageId
            ? { ...msg, content: streamContent }
            : msg
        ));
      }
    } finally {
      reader.releaseLock();
    }
  };

  // 处理普通响应（非流式）
  const handleNormalResponse = async (message: string) => {
    const response = await fetch("/api/agent", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message, agentType })
    });

    // 检查 HTTP 状态码
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();

    if (result.success) {
      // 处理 ReActAgent 结果
      let content: string;
      if (agentType === "react") {
        const steps = result.data as AgentState[];
        if (!Array.isArray(steps) || steps.length === 0) {
          throw new Error("ReActAgent 返回了无效的结果");
        }
        
        const lastStep = steps[steps.length - 1];
        if (lastStep?.answer) {
          content = lastStep.answer;
        } else if (lastStep?.observation) {
          content = `处理完成。最后观察：${lastStep.observation}`;
        } else {
          content = "Agent 已完成处理，但未生成最终答案。";
        }
      } else {
        // 处理 MultiAgent 结果
        const multiResult = result.data as CollaborateResult;
        if (!multiResult || typeof multiResult !== 'object' || !('final_answer' in multiResult)) {
          throw new Error("MultiAgentSystem 返回了无效的结果");
        }
        content = multiResult.final_answer || "未生成最终答案";
      }

      const agentMessage: Message = {
        id: (Date.now() + 1).toString(),
        type: "agent",
        content,
        steps: agentType === "react" ? (result.data as AgentState[]) : undefined,
        timestamp: new Date()
      };
      setMessages(prev => [...prev, agentMessage]);
    } else {
      throw new Error(result.error || "未知错误");
    }
  };

  // 步骤渲染函数
  const renderStep = (step: AgentState, index: number) => (
    <div key={index} className="ml-4 mb-2 p-2 bg-gray-50 rounded">
      <div className="text-sm text-gray-600">步骤 {step.step + 1}</div>
      {step.thought && <div className="text-sm">思考：{step.thought}</div>}
      {step.action && <div className="text-sm">行动：{step.action}</div>}
      {step.actionInput && Object.keys(step.actionInput).length > 0 && (
        <div className="text-sm text-gray-500">参数：{JSON.stringify(step.actionInput)}</div>
      )}
      {step.observation && <div className="text-sm">观察：{step.observation}</div>}
      {step.answer && <div className="text-sm font-semibold text-green-600">答案：{step.answer}</div>}
    </div>
  );

  return (
    <div className="max-w-4xl mx-auto h-screen flex flex-col">
      <div className="p-4 border-b">
        <h1 className="text-2xl font-bold mb-4">智能 Agent 对话</h1>
        <div className="flex gap-4 items-center">
          <select
            value={agentType}
            onChange={(e) => setAgentType(e.target.value)}
            className="border rounded px-3 py-1"
          >
            <option value="react">ReAct Agent</option>
            <option value="multi">Multi-Agent</option>
          </select>
          
          {agentType === "react" && (
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={streamEnabled}
                onChange={(e) => setStreamEnabled(e.target.checked)}
                className="w-4 h-4"
              />
              <span className="text-sm">启用流式输出</span>
            </label>
          )}
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((message) => (
          <div key={message.id} className={`flex ${message.type === "user" ? "justify-end" : "justify-start"}`}>
            <div className={`max-w-3xl p-3 rounded-lg ${message.type === "user"
                ? "bg-blue-500 text-white"
                : "bg-gray-100"
              }`}>
              <div className="whitespace-pre-wrap">{message.content}</div>
              {message.steps && (
                <div className="mt-2">
                  <div className="text-sm font-semibold mb-2">执行步骤：</div>
                  {message.steps.map(renderStep)}
                </div>
              )}
              <div className="text-xs opacity-70 mt-1">
                {message.timestamp.toLocaleTimeString()}
              </div>
            </div>
          </div>
        ))}
        {loading && (
          <div className="flex justify-start">
            <div className="bg-gray-100 p-3 rounded-lg">
              <div className="flex items-center gap-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-900"></div>
                Agent 正在思考...
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="p-4 border-t">
        <div className="flex gap-2">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyPress={(e) => e.key === "Enter" && sendMessage()}
            placeholder="输入你的问题..."
            className="flex-1 border rounded px-3 py-2"
            disabled={loading}
          />
          <button
            onClick={sendMessage}
            disabled={loading || !input.trim()}
            className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  );
}
